using System;
using System.IO;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;

namespace Microsoft.Samples.BizTalk.Adapter.Tcp
{
    /// <summary>
    ///     This class implements helper functions for saving dead messages into a folder.
    /// </summary>
    /// <author>
    ///     Paul Brown
    /// </author>
    public class DeadMessage
    {
        #region Public Constants

        public const string DeadMessageFileExtension = "msg";

        #endregion

        #region Public Static Methods

        /// <summary>
        ///     This method writes the contents of the stream to the disk.
        /// </summary>
        public static void WriteStreamToDisk(IAdapter adapter, Stream stream)
        {
            // Variables
            int bytesRead;
            int offset = 0;
            byte[] buffer = new byte[1024];

            // Build filename
            string filename = adapter.DeadMessageFolder + @"\" + Guid.NewGuid().ToString() + "." + DeadMessage.DeadMessageFileExtension;

            if (adapter.TraceSwitch.TraceVerbose)
                TraceHelper.WriteEntry(TraceLevel.Verbose, ResourceConstants.SavingDataToDeadMessageFolder, filename);

            // Seek stream back to the beginning
            if (stream.CanSeek)
            {
                stream.Position = 0;
            }

            // Write stream out to file
            using (FileStream backingStream = new FileStream(filename, FileMode.Create, FileAccess.Write))
            {
                using (BinaryWriter writer = new BinaryWriter(backingStream, Encoding.UTF8))
                {
                    while ((bytesRead = stream.Read(buffer, offset, 1024)) > 0)
                    {
                        writer.Write(buffer, 0, bytesRead);
                        offset += bytesRead;

                        if (offset >= stream.Length)
                        {
                            break;
                        }
                    }
                }
            }
        }

        #endregion
    }
}
